package services

import (
	"context"
	"fmt"
	"wxapi/internal/svc"
	"wxapi/models"
)

func notifyReadKey(id int64) string {
	return fmt.Sprintf("Notify:%d", id)
}

func GetSystemNotify(ctx context.Context, svc *svc.ServiceContext, userId int64) ([]*models.SystemNotify, error) {
	list := make([]*models.SystemNotify, 0)

	svc.Mysql.Model(&models.SystemNotify{}).Where("now() BETWEEN begin_time AND end_time AND state = 100").Order("`order`").Find(&list)

	for i := 0; i < len(list); i++ {
		key := notifyReadKey(list[i].ID)
		exists, _ := svc.Redis.HExists(ctx, key, fmt.Sprintf("%d", userId)).Result()
		if exists {
			list = append(list[:i], list[i+1:]...)
			i--
		}
	}

	return list, nil
}

func ReadSystemNotify(ctx context.Context, svc *svc.ServiceContext, notifyId, userId int64) {
	_, _ = svc.Redis.HSet(ctx, notifyReadKey(notifyId), userId, 1).Result()
}
